$(function () {
    window.projectType = 1;
    var showContentLoading = function () {
        $('.content-panel .content-panel-loading').removeClass('hidden');
    };
    var hideContentLoading = function () {
        $('.content-panel .content-panel-loading').addClass('hidden');
    };
    // 选择日期配置
    var format = 'YYYY-MM-DD';
    // 选择日期
    $('#datePickerInput').daterangepicker({
        'showDropdowns': true,
        'autoApply': true,
        'dateLimit': {
            'days': 30
        },
        'locale': {
            'format': format,
            'applyLabel': lang('date.ensure'),
            'cancelLabel': lang('date.cancel'),
            'daysOfWeek': [
                lang('week.7'),
                lang('week.1'),
                lang('week.2'),
                lang('week.3'),
                lang('week.4'),
                lang('week.5'),
                lang('week.6')
            ],
            'monthNames': [
                lang('month.1'),
                lang('month.2'),
                lang('month.3'),
                lang('month.4'),
                lang('month.5'),
                lang('month.6'),
                lang('month.7'),
                lang('month.8'),
                lang('month.9'),
                lang('month.10'),
                lang('month.11'),
                lang('month.12')
            ],
            'firstDay': 1
        },
        'linkedCalendars': false,
        'parentEl': 'body',
        'startDate': $('#datePicker').find('.start').html(),
        'endDate': $('#datePicker').find('.end').html(),
        'minDate': '2000-01-01',
        'maxDate': '2038-01-01',
        'opens': 'left'
    }, function (start, end, label) {
        $('#datePicker').find('.start').html(start.format(format));
        $('#datePicker').find('.end').html(end.format(format));
        refreshPage();
    });
    $('#datePickerContainer').on('click', function () {
        $('#datePickerInput').trigger('focus');
    });
    var refreshPage = function () {
        var startDate = $('#datePicker').find('.start').html();
        var endDate = $('#datePicker').find('.end').html();
        var param = {};
        param.hotel = window.currentHotel;
        param.start = startDate;
        param.end = endDate;
        param.type = window.projectType;
        showContentLoading();
        ajaxRequest('/Home/Report/getAccountView', param, 'post', function (data) {
            var info = data.data;
            // 订单明细
            var orderInfos = info.account;
            var total = info.total;
            var pages = info.pages;
            var currentPage = info.current;
            // 财务收支
            var financeOverview = $('#statisticOverview');
            financeOverview.find('span[data-tag="surplus"]').html(info.notesurplus);
            financeOverview.find('span[data-tag="income"]').html(info.income);
            financeOverview.find('span[data-tag="outcome"]').html(info.outcome);
            // 表格渲染
            refreshTable(orderInfos);
            refreshPageFooter(currentPage, pages, total);
            $('#orderInfoContaienr .content-panel-operation').find('a').attr('href', '/Home/Report/exportNoteCost?hotel=' + window.currentHotel + '&start=' + $('#datePicker').find('.start').html() + '&end=' + $('#datePicker').find('.end').html() + '&type=' +window.projectType);
            hideContentLoading();
        }, function (error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    };    
    var refreshTable = function (orderInfos) {
        var trs = '';
        var templateOriginal = $('#templateOrderPayRecord');
        $.each(orderInfos, function (index, info) {
            var template = $(templateOriginal.clone().html());
            template.find('[data-tag="date"]').html(info.noteDate);
            template.find('[data-tag="name"]').html(info.noteName);
            template.find('[data-tag="total"]').html(info.notePrice);
            template.find('[data-tag="by"]').html(info.notePay);
            template.find('[data-tag="remark"]').html(info.noteRemark);
            template.find('[data-tag="operation"]').html(info.noteOperator);
            template.find('[data-tag="operate"]').attr('data-value',info.id);
            trs += template.prop('outerHTML');
        });
        $('#orderInfoTbody').html(trs);
    };
    var refreshPageFooter = function (currentPage, pages, total) {
        currentPage = parseInt(currentPage);
        pages = parseInt(pages);
        total = parseInt(total);
        var pageItems = '';
        for (var i = 1; i <= pages; i++) {
            if (i === currentPage) {
                pageItems += '<li class="active"><a href="javascript:void(0);" data-value="' + i + '">' + i + '</a></li>';
            } else {
                pageItems += '<li><a href="javascript:void(0);" data-value="' + i + '">' + i + '</a></li>';
            }
        }
        $('#orderInfoContaienr').find('.pagination').html(pageItems);
        $('#orderInfoContaienr').find('.content-panel-pagination-count').html(total);
    };
    refreshPage();
    // 点击分页地址
    $('#orderInfoContaienr .pagination').on('click', 'li:not(.active)>a', function (e) {
        e.preventDefault();
        var pageLink = $(this);
        var param = {};
        param.hotel = window.currentHotel;
        param.current = pageLink.data('value');
        param.start = $('#datePicker').find('.start').html();
        param.end = $('#datePicker').find('.end').html();
        param.type = window.projectType;
        $('#orderInfoContaienr .content-panel-loading').removeClass('hidden');
        ajaxRequest('/Home/Report/getAccountViewData', param, 'post', function (data) {
            var info = data.data;
            // 订单明细
            var orderInfos = info.account;
            var total = info.total;
            var pages = info.pages;
            var currentPage = info.currentPage;
            // 表格渲染
            refreshTable(orderInfos);
            refreshPageFooter(currentPage, pages, total);
            $('#orderInfoContaienr .content-panel-loading').addClass('hidden');
        }, function (error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });

    $('.content-panel-project').on('click','.project-list',function(){
        $me = $(this);
        var value = $me.data('value');
        $me.addClass('active').siblings().removeClass('active');
        window.projectType = value;
        refreshPage();
    });      
    // 删除记录
    $('#deleteModal').on('show.bs.modal', function(e) {
        var triggerId = $(e.relatedTarget);
        window.noteId = triggerId.data('value');
    });
    // 删除记录model点击
    $('#submitBooksDelete').on('click', function (e) {
        var param = {
                hotel: window.currentHotel,
                noteCostId: window.noteId,
                delete:'delete'
            },
            $me = $(this);
        ajaxRequest('/Home/Hotel/editNoteCost', param, 'post', function(data){
            refreshPage();
            $('#deleteModal').modal('hide');
        }, null, $me);
    });    
    // 修改记录
    $('#booksTime').fdatepicker({
        format: 'yyyy-mm-dd',
        startDate: "2000-01-01",
        endDate: '2060-01-01',
    }); 
    $('.booksProjectTypeMenu').on('click','li',function(){
        var submitbtn = $(this); 
        submitbtn.addClass('active').siblings('li').removeClass('active');
        submitbtn.closest('.dropdown').find('.booksProjectType').attr('data-value',submitbtn.data('value')).find('.info').text(submitbtn.find('a').text());
    });  
    $('.booksReceiveTypeMenu').on('click','li',function(){
        var submitbtn = $(this); 
        submitbtn.addClass('active').siblings('li').removeClass('active');
        $('#booksReceiveType').attr('data-value',submitbtn.data('value')).find('.info').text(submitbtn.find('a').text());
    });    
    $('#orderInfoContaienr').on('click','.booksRecordEdit', function() {
        var triggerId = $(this);
        var param = {};
        param.hotel = window.currentHotel;
        param.noteCostId = triggerId.data('value');
        ajaxRequest('/Home/Hotel/getNoteCost', param, 'post', function (data) {
            var info = data.data;
            $('#booksPrice').val(info.notePrice);
            $('#booksTime').val(info.noteDate);
            $('.booksProjectType').attr('data-value',info.noteId).find('.info').text(info.noteName)
            $('#booksReceiveType').attr('data-value',info.payId).find('.info').text(info.notePay);
            $('#booksRemark').val(info.noteRemark);
            $('#confirmBooksInfo').attr('data-value',info.noteCostId);
            $('#confirmBooksInfo').attr('data-type',info.type);
        }, function (error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });    
    $('#confirmBooksInfo').on('click',function(){
        var submitBtn = $(this);
        var price = $('#booksPrice').val().trim();
        if(price == ''){
            formInlineTip(submitBtn, lang('constant.sumNull'));
            return false;
        }
        var param = {
                hotel: window.currentHotel,
                noteCostId:submitBtn.data('value'),
                noteId: $('.booksProjectType').attr('data-value'),
                payId:$('#booksReceiveType').attr('data-value'),
                type: submitBtn.attr('data-type'),
                price:price,
                noteDate:$('#booksTime').val(),
                remark:$('#booksRemark').val()
        };
        ajaxRequest('/Home/Hotel/editNoteCost', param, 'post',function(data){
            refreshPage();
            $('#booksModal').modal('hide');
        }, function(error) {
            if (error.responseJSON === undefined) {
                formInlineTip(submitBtn, lang('tip.server'));
            } else {
                formInlineTip(submitBtn, error.responseJSON.info);
            }
        }, submitBtn);      
    })    
    // 可移动模态框
    interact('.modal-header').ignoreFrom('input, textarea').draggable({
        restrict: {
            restriction: 'body',
            endOnly: true
        },
        autoScroll: false,
        onmove: function dragMoveListener(event) {
            var target = event.target,
                x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
                y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
            var targetMovable = $(target).parent();
            var translate = 'translate(' + x + 'px, ' + y + 'px)';
            targetMovable.css('-webkit-transform', translate);
            targetMovable.css('transform', translate);
            target.setAttribute('data-x', x);
            target.setAttribute('data-y', y);
        },
        onend: function(event) {
            var target = event.target,
                x = parseFloat(target.getAttribute('data-x')) || 0,
                y = parseFloat(target.getAttribute('data-y')) || 0;
            var targetMovable = $(target).parent(),
                offsetX = parseInt(targetMovable.css('left')) || 0,
                offsetY = parseInt(targetMovable.css('top')) || 0;
            target.setAttribute('data-x', 0);
            target.setAttribute('data-y', 0);
            targetMovable.css('-webkit-transform', '');
            targetMovable.css('transform', '');
            targetMovable.css('left', offsetX + x + 'px');
            targetMovable.css('top', offsetY + y + 'px');
        }
    });
});
